<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/10/22
 * Time: 16:01
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\common\business;


use app\common\lib\Show;
use app\common\lib\Status;
use app\common\validate\GrabSheet as ValObj;
use app\common\model\mysql\GrabSheet as ModelObj;
use think\Exception;
use think\facade\Log;

class GrabSheet extends Base
{
    /**
     * @var ValObj
     */
    protected ValObj $valObj;
    /**
     * @var ModelObj
     */
    protected ModelObj $modelObj;

    /**
     *
     */
    public function __construct()
    {
        $this->valObj = new ValObj();
        $this->modelObj = new ModelObj();
    }

    public function getGrabOrder(int $type = 0, int $limit = 10, int $page = 1, string $openid = '*')
    {
        $map[] = [
            ['openid', '=', $openid]
        ];
        if ($type != 99) {
            $map[] = [
                ['state', '=', $type]
            ];
        }
        try {
            $lists = $this->modelObj->getGrabOrder($map, $limit, $page);
        } catch (\Exception $e) {
            Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            throw new Exception("查询失败");
        }
        return $lists;
    }

    /**
     * 骑手修改配送状态
     * @param int $id
     * @param int $type
     * @return bool
     * @throws Exception
     */
    public function setGrabByData(int $id = 0, int $type = 0): bool
    {
        if (!in_array($type, [1, 2, 3])) {
            throw new Exception("类型错误");
        }
        $grab = $this->getBaseById($id, '*,order_id as ret_id');

        if (!$grab) {
            throw new Exception("订单不存在");
        }
        if ($grab['state'] == $type) {
            throw new Exception("内部错误");
        }
        $objModel = new \app\common\model\mysql\GrabSheet();

        $objModel->startTrans();
        $state = 3;
        $stateKey = 'state_time';
        if ($type == 3) {
            $state = 4;
            $stateKey = 'end_time';
        }
        try {
            $grab->save([
                "state" => $type,
                $stateKey => time()
            ]);
            (new PlaceOrder())->updateByData((int)$grab['ret_id'], [
                "state" => $state,
                $stateKey => time()
            ]);
            if ($type == 3) {
                (new Money())->add([
                    "openid" => $grab['openid'],
                    "money" => $grab['money'],
                    "type" => 1
                ]);
            }
            $objModel->commit();
        } catch (\Exception $e) {
            $objModel->rollback();
            Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            throw new Exception("系统错误");
        }
        return true;

    }

}